// api.ts 或 axiosConfig.ts
import type { AxiosResponse } from 'axios'
import { getStorage } from '@/utils/storage'
import axios from 'axios'
import { message } from 'antd'
import type { NavigateFunction } from 'react-router-dom'

let navigate: (path: string, options?: { replace?: boolean }) => void
export const setNavigate = (val: NavigateFunction) => {
  navigate = val
}

// @ts-ignore
const baseURL = import.meta.env.VITE_BASE_URL
// 创建 Axios 实例
const http = axios.create({
  baseURL,
  timeout: 60000 // 设置请求超时时间
})

// 添加请求拦截器
http.interceptors.request.use(
  (config) => {
    // 在发送请求之前做些什么
    // 例如，添加请求头、身份验证等
    const localuserInfo = getStorage('user-info')
    config.headers.Authorization = localuserInfo?.token || ''
    return config
  },
  (error) => {
    // 对请求错误做些什么
    console.error('Request interceptor error:', error)
    return Promise.reject(error)
  }
)

// 添加响应拦截器
const needHeaderUrl = [
  '/disp/biz/order/export',
  '/disp/biz/order/exportSeatTeamOrder',
  '/disp/biz/order/exportInvitationOrder',
  '/disp/biz/order/exportIntentionalOrder',
  '/disp/biz/order/exportRecyclingOrder',
  '/disp/biz/order/exportPendingConfirmationOrder',
  '/disp/biz/analysis/exportDataStatisticsForSeat',
  '/disp/biz/analysis/exportDataStatisticsForBiz'
]
http.interceptors.response.use(
  (res: AxiosResponse) => {
    if (needHeaderUrl.includes(res.config.url as string)) {
      return res
    }
    if (res.data.code === 200) {
      return res.data
    } else if (res.data.code === 401){
      navigate('/login', { replace: true })
      return Promise.reject(new Error(res.data.msg || '暂无权限'))
    }
    return Promise.reject(res.data || res)
  },
  (error) => {
    if (error.status === 401) {
      message.error('身份已失效，请重新登录', 1).then(() => {
        navigate('/login', { replace: true })
      })
    } else {
      return Promise.reject(error)
    }
  }
)

export default http